<!-- author: lizq -->
<!-- date: 2023-03-01 15:09:44 -->
<!-- description: table - 新增、编辑 -->
<!-- eslint-disable vue/no-mutating-props -->
<template>
  <div class="addForm">
    <!-- form -->
    <el-form
      ref="addFormRef"
      :model="formData"
      :disabled="disabled"
      :label-position="labelPosition"
      :rules="formRules"
      :label-width="labelWidth"
      :hide-required-asterisk="hideRequiredAsterisk"
      @submit.enter.prevent
    >
      <el-row :gutter="20">
        <template v-for="(item, i) in formDataInfo" :key="i">
          <el-col v-if="item.type == 'formcol'" :span="24">
            <slot name="formCol"></slot>
          </el-col>
          <!-- 自定义表单项 -->
          <el-col v-else-if="item.type == 'slotFormCol'" :span="singleRow ? 24 : spanNum(i, item.span)">
            <slot :name="item.prop" :row="item" :label-width="labelWidth"></slot>
          </el-col>
          <el-col v-else :span="singleRow ? 24 : spanNum(i, item.span)">
            <!-- form-item -->
            <el-form-item v-if="item.show === false ? false : true" :label-width="item.labelWidth || labelWidth" :label="item.label" :prop="item.prop">
              <!-- input -->
              <el-input
                v-if="item.type == 'input'"
                v-model="formData[item.prop]"
                v-maxLength="item.max"
                :disabled="item.disabled ? true : false"
                :placeholder="item.placeholder ? item.placeholder : '请输入'"
                clearable
              />
              <!-- select -->
              <el-select
                v-else-if="item.type == 'select'"
                v-model="formData[item.prop]"
                :disabled="item.disabled"
                placeholder="请选择"
                clearable
                :allow-create="item.allowCreate"
                :filterable="item.filterable"
                :multiple="item.multiple ? true : false"
                @change="formChange(i, item)"
              >
                <template v-if="item.dict">
                  <el-option v-for="dict in dicts[item.dict]" :key="dict.value" :label="dict.label" :value="dict.value" />
                </template>
                <template v-else-if="item.options">
                  <el-option v-for="dict in item.options" :key="dict.value" :label="dict.label" :value="dict.value" />
                </template>
              </el-select>
              <!-- date -->
              <el-date-picker
                v-else-if="item.type == 'date'"
                v-model="formData[item.prop]"
                :disabled="item.disabled"
                :type="item.dateInfo ? item.dateInfo.type : 'date'"
                :format="item.dateInfo ? item.dateInfo.format : 'YYYY-MM-DD'"
                :value-format="item.dateInfo ? item.dateInfo.vFormat : 'YYYY-MM-DD'"
                :unlink-panels="item.dateInfo ? item.dateInfo.unlink : false"
                range-separator="-"
                start-placeholder="开始"
                end-placeholder="结束"
                placeholder="请选择"
              />
              <!-- textarea -->
              <el-input
                v-else-if="item.type == 'textarea'"
                v-model="formData[item.prop]"
                :disabled="item.disabled ? true : false"
                maxlength="200"
                type="textarea"
                show-word-limit
                :autosize="{ minRows: 3 }"
                placeholder="请输入"
              />
              <!-- number -->
              <el-input
                v-else-if="item.type == 'number'"
                v-model="formData[item.prop]"
                :disabled="item.disabled ? true : false"
                type="number"
                placeholder="请输入"
              >
                <template v-if="item.unit" #append>
                  <div>{{ item.unit }}</div>
                </template>
              </el-input>
              <!-- radio -->
              <el-radio-group v-else-if="item.type == 'radio'" v-model="formData[item.prop]">
                <template v-if="item.dict">
                  <el-radio v-for="dict in dicts[item.dict]" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                  <!-- <el-option v-for="a in dicts[item.dict]" :key="a.value" :label="a.label" :value="a.value" /> -->
                </template>
                <template v-else-if="item.options">
                  <el-radio v-for="dict in item.options" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
                  <!-- <el-option v-for="dict in item.options" :key="a.value" :label="a.label" :value="a.value" /> -->
                </template>
              </el-radio-group>
              <!-- 富文本编辑器 -->
              <G-wang-editor
                v-else-if="item.type == 'editor'"
                ref="wangEditorRef"
                v-model="formData[item.prop]"
                @change-content="changeContent(formData[item.prop], item.prop)"
              ></G-wang-editor>
              <!-- slot -->
              <slot v-else-if="item.type == 'slot'" :name="item.prop"></slot>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <!-- but -->
    <div v-if="showFooter" class="footer">
      <el-button type="primary" @click="onSubmit(1)">{{ confirmButtonText }}</el-button>
      <el-button @click="onSubmit">返回</el-button>
    </div>
  </div>
</template>

<script setup>
const $props = defineProps({
  formData: {
    type: Object,
    default: () => {}
  },
  formRules: {
    type: Object,
    default: () => {}
  },
  formDataInfo: {
    type: Array,
    default: () => []
  },
  singleRow: {
    type: Boolean,
    default: false
  },
  showFooter: {
    type: Boolean,
    default: true
  },
  labelPosition: {
    type: String,
    default: "right"
  },
  labelWidth: {
    type: String,
    default: "100px"
  },
  confirmButtonText: {
    type: String,
    default: "确认"
  },
  disabled: {
    type: Boolean,
    default: false
  },
  hideRequiredAsterisk: {
    type: Boolean,
    default: false
  }
});
const $emit = defineEmits(["callBackData", "formChange", "update:formData"]);

const formData = computed({
  get: () => {
    return $props.formData;
  },
  set: (val) => $emit("update:formData", val)
});

//初始化-字典数据
const { proxy } = getCurrentInstance();
const dictList = ref([]);
const dicts = ref([]);
$props.formDataInfo.forEach((item) => {
  if (item.dict) {
    dictList.value.push(item.dict);
  }
});

if (dictList.value.length > 0) {
  dicts.value = proxy.useDict(dictList.value);
}

watch(
  () => $props.formDataInfo,
  (newVal) => {
    newVal.forEach((item) => {
      if (item.dict) {
        dictList.value.push(item.dict);
      }
    });
    dicts.value = proxy.useDict(dictList.value);
  }
);
const addFormRef = ref(null);
//form表单change事件
const formChange = (i, item) => {
  $emit("formChange", $props.formData[item.prop], i, item);
};

const wangEditorRef = ref(null);
const isNull = (str) => {
  if (str == "") {
    return true;
  }
  let regu = "^[ ]+$";
  let re = new RegExp(regu);
  return re.test(str);
};
// 获取富文本内容
const changeContent = (val, propName) => {
  // console.log(val, "富文本内容", formData.value);
  let text = wangEditorRef.value[0].getText();
  console.log(val, propName, text, "-=---==-=-=-");
  if (!isNull(text)) {
    // 如果编辑框有内容
    formData.value[propName] = val;
  } else {
    formData.value[propName] = null;
  }

  // if (val == null) {
  //   formData.value.content = null;
  // } else {
  //   formData.value.content = val;
  // }
  // 重新进行表单校验
  addFormRef.value.validateField(propName);
};

//确认
const onSubmit = (val) => {
  console.log($props.formData, "=2=");
  if (val == 1) {
    addFormRef.value.validate((valid, fields) => {
      if (valid) {
        $emit("callBackData", $props.formData);
      } else {
        console.log("error submit!", fields);
      }
    });
  } else {
    $emit("callBackData", "");
  }
};

//校验返回
const validateForm = async (val) => {
  let returnB = false;
  if (val == 1) {
    await addFormRef.value.validate((valid, fields) => {
      if (valid) {
        $emit("callBackData", $props.formData);
        returnB = true;
      } else {
        console.log("error submit!", fields);
        returnB = false;
      }
    });
  } else {
    $emit("callBackData", "");
  }

  return returnB;
};

//重置表单
const resetForm = () => {
  addFormRef.value.resetFields();
};

//计算span值
const spanNum = computed(() => (index, span) => {
  //   console.log(index);
  //   console.log(span);

  if (span) {
    return span;
  } else {
    console.log(123);

    return index == $props.formDataInfo.length - 1 && $props.formDataInfo.length % 2 == 1 ? 24 : 12;
  }
});

defineExpose({ addFormRef, onSubmit, resetForm, validateForm });
</script>

<style scoped lang="scss">
.addForm {
  box-sizing: border-box;
}

//input
:deep(.el-form-item) {
  margin-bottom: 20px !important;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-cascader) {
  width: 100%;
}

//富文本 修改
:deep(.w-e-text-container) {
  height: 400px;
}
</style>
